package cn.wolfcode.interceptor;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.util.RequiredPermission;
import cn.wolfcode.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class PermissionInterceptor implements HandlerInterceptor {
    @Autowired
    private IPermissionService permissionService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从作用域中拿到当前用户对象
        Employee employee = UserContext.getCurrentUser();
        //从作用域中拿出员工的权限表达式列表
        List<String> expressions = UserContext.getExpression();
        //查询出员工是否为超级管理员
        if (employee.isAdmin()){
            //是,直接放行
            return true;
        }
        //不是管理员,先获取请求的方法,看是否需要访问权限
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        //获取到注解对象
        RequiredPermission annotation = handlerMethod.getMethodAnnotation(RequiredPermission.class);
        //如果注解对象为null说明没贴权限注解,可直接放行
        if (annotation==null){
            return true;
        }
        //执行到这里说明此方法有权限设置,拿取到注解对象的表达式,看是否在员工的权限表达式集合中
        if (expressions.contains(annotation.expression())){
            //在说明有权限,可以访问,放行
            return true;
        }else {
            //不在说明没有权限,重定向到没有权限界面,不放行
            request.getRequestDispatcher("/WEB-INF/views/common/nopermission.jsp").forward(request, response);
            return false;
        }
    }
}
